/*
 * Copyright 2007 - The JDPF Project Team (http://www.jdpf.org) 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package org.jdpf.core.contextmanager.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.jdpf.core.contextmanager.TaskManager;
import org.jdpf.core.kernel.execution.Task;
import org.jdpf.core.kernel.logging.ILogger;
import org.jdpf.core.kernel.logging.LoggerFactory;

public class FileTaskHandler implements ITaskHandler {

	private static final ILogger logger = LoggerFactory.getDefault()
			.getLogger();

	private String workspace;

	private TaskManager tm;
	private List<String> projects;

	public static final String NETS_FILE = ".nets";

	public static final String TASKS_FILE = ".tasks";

	public FileTaskHandler() {

	}

	public void setWorkspace(String workspace) {
		this.workspace = workspace;
		logger.log("\n\n---------------------------------");
		logger.log("JDPF current workspace " + this.workspace);
		logger.log("---------------------------------\n\n");
		projects = new ArrayList<String>(5);

		File[] files = new File(this.workspace).listFiles();
		if (files!=null)
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory() && !files[i].getName().startsWith("."))
					projects.add(this.workspace + files[i].getName()
							+ File.separator);
			}
	}

	public void listAllTasks() {
		for (String project : projects) {
			File f = new File(project + TASKS_FILE);
			if (f.exists()) {
				try {
					BufferedReader br = new BufferedReader(new FileReader(f));
					String line;
					while ((line = br.readLine()) != null) {
						StringTokenizer st = new StringTokenizer(line, ";");
						if (st.hasMoreTokens()) {
							String netFile = st.nextToken();
							String paramFile = st.nextToken();

							tm.addTaskToList(project + netFile, project
									+ paramFile);
						}
					}
					br.close();
				} catch (IOException e) {
					logger.error(this, e.getMessage());
				}
			}
		}
	}

	public void listAllNets() {
		for (String project : projects) {
			File f = new File(project + NETS_FILE);
			if (f.exists()) {
				try {
					BufferedReader br = new BufferedReader(new FileReader(f));
					String line;
					while ((line = br.readLine()) != null) {
						tm.addNetToList(project + line);
					}
					br.close();
				} catch (IOException e) {
					logger.error(this, e.getMessage());
				}
			}

		}
	}

	public void addNet(String net, String project) {
		File f = new File(workspace + project + File.separator + NETS_FILE);
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append('\n');
			}
			br.close();
			sb.append(net.substring(net.lastIndexOf(File.separator) + 1));
			FileWriter fw = new FileWriter(f);
			fw.append(sb.toString());
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addTask(Task t, String project) {
		File f = new File(workspace + project + File.separator + TASKS_FILE);
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append('\n');
			}
			br.close();
			sb.append(t.getNetFile().substring(
					t.getNetFile().lastIndexOf(File.separator) + 1));
			sb.append(';');
			sb.append(t.getParamFile().substring(
					t.getParamFile().lastIndexOf(File.separator) + 1));
			sb.append('\n');
			FileWriter fw = new FileWriter(f);
			fw.append(sb.toString());
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void removeNet(String net, String project) {
		File f = new File(workspace + project + File.separator + NETS_FILE);
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line;
			while ((line = br.readLine()) != null) {
				if (!line.equals(net
						.substring(net.lastIndexOf(File.separator) + 1))) {
					sb.append(line);
					sb.append('\n');
				}
			}
			br.close();
			FileWriter fw = new FileWriter(f);
			fw.append(sb.toString());
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File netFile = new File(net);
		netFile.delete();
	}

	public void removeTask(Task t, String project) {
		File f = new File(workspace + project + File.separator + TASKS_FILE);
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(f));
			String line;
			while ((line = br.readLine()) != null) {
				StringTokenizer st = new StringTokenizer(line, ";");
				String net = st.nextToken();
				String param = st.nextToken();
				if (!param.equals(t.getParamFile().substring(
						t.getParamFile().lastIndexOf(File.separator) + 1))
						|| !net
								.equals(t.getNetFile().substring(
										t.getNetFile().lastIndexOf(
												File.separator) + 1))) {
					sb.append(line);
					sb.append('\n');
				}
			}
			br.close();
			FileWriter fw = new FileWriter(f);
			fw.append(sb.toString());
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File paramFile = new File(t.getParamFile());
		paramFile.delete();
	}

	public void addTaskManger(TaskManager manager) {
		tm = null;
		this.tm = manager;
	}

}
